<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <label class="el-form-item-label">卡号</label>
        <el-input
          v-model="query.no"
          clearable
          placeholder="卡号"
          style="width: 185px;"
          class="filter-item"
          type="number"
          @keyup.enter.native="crud.toQuery"
        />
        <label class="el-form-item-label">使用者</label>
        <el-select
          v-model="query.userId"
          placeholder="请选择"
          style="width: 185px;"
          clearable
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        >
          <el-option v-for="item in users" :key="item.id" :label="item.username" :value="item.id" />
        </el-select>
        <label class="el-form-item-label">创建者</label>
        <el-select
          v-model="query.creatorId"
          placeholder="请选择"
          style="width: 185px;"
          clearable
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        >
          <el-option v-for="item in users" :key="item.id" :label="item.username" :value="item.id" />
        </el-select>
        <!-- <label class="el-form-item-label">状态</label> -->
        <!-- <el-input v-model="query.status" clearable placeholder="状态" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" /> -->
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <!--表单组件-->
      <el-dialog
        v-if="crud.status.cu > 0"
        :close-on-click-modal="false"
        :before-close="crud.cancelCU"
        :visible="crud.status.cu > 0"
        :title="crud.status.title"
        width="500px"
      >
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          size="small"
          label-width="80px"
        >
          <el-form-item label="卡号" prop="no">
            <el-input v-model="form.no" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="使用者" prop="userId">
            <el-select
              v-model="form.userId"
              placeholder="请选择"
              style="width: 370px;"
            >
              <el-option v-for="item in users" :key="item.id" :label="item.username" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="有效期" prop="expiredAt">
            <el-date-picker v-model="form.expiredAt" type="datetime" style="width: 370px;" :picker-options="pickerOptions" placeholder="选择日期" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select
              v-model="form.status"
              placeholder="请选择"
              style="width: 370px;"
            >
              <el-option label="禁用" :value="0" />
              <el-option label="激活" :value="1" />
            </el-select>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="form.note" style="width: 370px;" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button
            :loading="crud.status.cu === 2"
            type="primary"
            @click="crud.submitCU"
          >确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table
        ref="table"
        v-loading="crud.loading"
        :data="crud.data"
        size="small"
        style="width: 100%;"
        @selection-change="crud.selectionChangeHandler"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="no" label="卡号" />
        <el-table-column prop="userId" label="使用者" :formatter="formatterUser" />
        <el-table-column prop="expiredAt" label="有效期" />
        <el-table-column prop="createName" label="创建者" />
        <el-table-column prop="note" label="备注" />
        <!-- <el-table-column prop="status" label="状态" /> -->
        <el-table-column
          v-if="
            checkPer([
              'admin',
              'entranceGuardCard:edit',
              'entranceGuardCard:del'
            ])
          "
          class-name="operation"
          label="操作"
          width="180px"
          align="center"
        >
          <template slot-scope="scope">
            <udOperation
              ref="udOperation"
              :data="scope.row"
              :permission="permission"
            />
            <el-button
              type="success"
              class="isForbiddenBtn"
              @click.native="IsForbidden(scope.row)"
            >{{ scope.row.status ? "禁用" : "激活" }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import { editStatus } from '@/api/entranceGuardCard.js'
import getAllUserAndLabs from '@/mixins/getAllUserAndLabs.js'
import crudEntranceGuardCard from '@/api/entranceGuardCard'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'

const defaultForm = {
  id: null,
  no: null,
  userId: null,
  expiredAt: null,
  note: null,
  creatorId: null,
  status: 1,
  createdAt: null,
  updatedAt: null,
  isDeleted: null
}
export default {
  name: 'EntranceGuardCard',
  components: { pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud(), getAllUserAndLabs],
  cruds() {
    return CRUD({
      title: '门禁卡',
      url: 'api/entranceGuardCard',
      idField: 'id',
      sort: 'id,desc',
      crudMethod: { ...crudEntranceGuardCard }
    })
  },
  data() {
    const limitNumber = (rule, value, callback) => {
      if (value) {
        if (!Number.isInteger(+value)) {
          callback(new Error('必须全为数字'))
        }
        //  else if (value.trim().length < 8 || value.trim().length > 12) {
        //   callback(new Error('数字长度必须在8到12之间'))
        // }
        else {
          callback()
        }
      } else if (rule.required) {
        // 如果没值又是必填
        callback(new Error(rule.msg))
      } else {
        callback()
      }
    }
    return {
      permission: {
        add: ['admin', 'entranceGuardCard:add'],
        edit: ['admin', 'entranceGuardCard:edit'],
        del: ['admin', 'entranceGuardCard:del']
      },
      rules: {
        no: [
          { validator: limitNumber, message: '请输入正确的数据格式', trigger: 'blur' },
          { required: true, message: '卡号不能为空', trigger: 'blur' }
        ],
        userId: [
          { required: true, message: '使用者不能为空', trigger: 'blur' }
        ],
        expiredAt: [
          { required: true, message: '有效期不能为空', trigger: 'blur' }
        ],
        status: [{ required: true, message: '请选择状态', trigger: 'blur' }]
      },
      queryTypeOptions: [
        { key: 'no', display_name: '卡号' },
        { key: 'userId', display_name: '使用者' },
        { key: 'creatorId', display_name: '创建者' },
        { key: 'status', display_name: '状态' }
      ],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
        }
      }
    }
  },
  created() {
    this.getUsers()
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    // 激活 还是 禁用
    async IsForbidden(val) {
      // 通过id 发送请求 修改 状态
      // console.log(111, val)
      const status = val.status ? 0 : 1
      try {
        await editStatus(val.id, status)
        val.status = status
      } catch (error) {
        this.$message('修改失败')
      }
    },
    [CRUD.HOOK.beforeDelete](crud, data) {
      const now = new Date().getTime()

      if (data instanceof Array) {
        const res = data.find(
          item => new Date(item.expiredAt).getTime() > now && item.status
        )
        if (res) {
          this.crud.notify(
            `卡号为${res.no}还在有效期内，请先禁用。`,
            CRUD.NOTIFICATION_TYPE.WARNING
          )
          this.crud.delAllLoading = false
          return false
        }
      } else {
        const time = new Date(data.expiredAt).getTime()
        if (time > now && data.status) {
          this.crud.notify(
            '还在有效期内，请先禁用。',
            CRUD.NOTIFICATION_TYPE.WARNING
          )
          if (this.$refs.udOperation) {
            this.$refs.udOperation.pop = false
          }
          return false
        }
      }
    },
    formatterUser(row) {
      const data = this.users.find(user => user.id == row.userId)
      if (data) {
        return data.username
      }
    }
  }
}
</script>

<style scoped lang="scss">
.el-table ::v-deep .cell {
  display: flex;
  align-items: center;

  .isForbiddenBtn {
    width: 43px;
    height: 28px;
    line-height: 28px;
    text-align: center;
    margin-left: 5px;
    padding: 0;
  }
}
</style>
